package com.hehui.partimejob.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.hehui.partimejob.websocket.WebClient;

import java.lang.reflect.ParameterizedType;

public class BaseWebView {

    public final String TAG = getClass().getSimpleName();
    private WebView wv;
    private BaseWebView baseWebView;
    private String url;
    private BaseWebChromeClient webChromeClient;
    private BaseWebViewClient webViewClient;
    private OnBaseWebViewListener listener;

    public String getUrl() {
        return url;
    }

    public WebView getWv() {
        return wv;
    }

    public void setWv(WebView wv) {
        this.wv = wv;
    }

    public BaseWebChromeClient getWebChromeClient() {
        return webChromeClient;
    }

    public void setWebChromeClient(BaseWebChromeClient webChromeClient) {
        this.webChromeClient = webChromeClient;
    }

    public BaseWebViewClient getWebViewClient() {
        return webViewClient;
    }

    public void setWebViewClient(BaseWebViewClient webViewClient) {
        this.webViewClient = webViewClient;
    }


    public void setListener(OnBaseWebViewListener listener) {
        this.listener = listener;
    }

    public BaseWebView(WebView webView) {
        this.wv = webView;
//        wv.setVisibility(View.INVISIBLE);
        baseWebView = this;
        webChromeClient = new BaseWebChromeClient();
        webViewClient = new BaseWebViewClient();
    }

    public void loadFromAsset(String url) {
        this.url = "file:///android_asset/" + url;
        init();
    }


    private void init() {
        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        wv.setWebChromeClient(webChromeClient);
        wv.setWebViewClient(webViewClient);
        wv.loadUrl(url);
    }

    public <T> void executeJsFunction(String functionName, CallBackFromJS<T> callBackFromJS, Object... param) {
        StringBuilder script = new StringBuilder();
        script.append("javascript:");
        script.append(functionName);

        script.append("(");
        for (Object o : param) {
            script.append("'");
            script.append(o);
            script.append("'");
            script.append(",");
        }
//        去掉最后一个逗号
        script.delete(script.length()-1,script.length());
        script.append(")");
        Log.d(TAG, "executeJsFunction: "+script.toString());

        wv.evaluateJavascript(script.toString(), callBackFromJS != null ? new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                T t = new Gson().fromJson(value, callBackFromJS.getType());
                if (t != null) {
                    callBackFromJS.valueCallback(t);
                }
            }
        } : null);
    }


    public <T> void executeJsFunction(String functionName, CallBackFromJS<T> callBackFromJS) {
        executeJsFunction(functionName, callBackFromJS, (Object) null);
    }

    public void executeJsFunction(String functionName, Object... param) {
        executeJsFunction(functionName, null, param);
    }

    public void executeJsFunction(String functionName) {
        executeJsFunction(functionName, null, (Object) null);
    }


    public abstract static class CallBackFromJS<T> {
        protected Class<T> clazz;

        //    通过反射 将T转成Class
        public Class<T> getType() {
            return clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }

        public abstract void valueCallback(T value);
    }


    @SuppressLint("JavascriptInterface")
    public void addJavascriptInterface(Object object) {
        wv.addJavascriptInterface(object, object.getClass().getSimpleName());
    }

    public static class BaseWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    }

    public class BaseWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest resourceRequest) {
            Log.d(TAG, "shouldOverrideUrlLoading: " + resourceRequest.getUrl());
//           wv.setBackgroundColor(Color.argb(1, 0, 0, 0));
            view.loadUrl(resourceRequest.getUrl().toString());// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
            return true;
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            wv.setBackgroundColor(Color.TRANSPARENT);
//            wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
//            wv.setVisibility(View.VISIBLE);
            if (listener != null) {
                listener.onPageFinished(baseWebView);
            }
        }
    }

    public interface OnBaseWebViewListener {
        /**
         * baseWebView 加载完成时调用该方法
         */
        void onPageFinished(BaseWebView webView);
    }
}
